﻿using System;
using System.Diagnostics;
using System.IO;
using System.ServiceModel;
using Aspose.Cells;
using Aspose.Cells.Rendering;

namespace BookingEngine.ExcelService
{
    [ServiceBehavior(ConfigurationName = "AsposeExcelConvertService", Namespace = "http://www.hubs1.net")]
    public class AsposeExcelConvertService : IExcelConverter
    {
        #region Implementation of IExcelConversionService

        public byte[] ConvertToPdf(byte[] excelFile, bool isLandscape)
        {
            var excelFileStream = new MemoryStream(excelFile);
            var workBook = new Workbook(excelFileStream);
            foreach (Worksheet worksheet in workBook.Worksheets)
            {
                worksheet.PageSetup.Orientation = isLandscape ? PageOrientationType.Landscape : PageOrientationType.Portrait;
                worksheet.PageSetup.PaperSize = PaperSizeType.PaperA4;
                worksheet.PageSetup.CenterHorizontally = true;
                worksheet.PageSetup.PrintQuality = 300;
                worksheet.PageSetup.LeftMargin = 1.0;
                worksheet.PageSetup.RightMargin = 1.0;
                worksheet.PageSetup.FitToPagesWide = 1;
                worksheet.PageSetup.FitToPagesTall = 0;
            }
            var saveOptions = new PdfSaveOptions(SaveFormat.Pdf)
                                  {
                                      Compliance = PdfCompliance.None,
                                      OnePagePerSheet = false
                                  };

            if (isLandscape)
            {
                var guid = Guid.NewGuid();
                var path = string.Format(@"C:\Pdk\Temp\Input\{0}.pdf", guid);
                var outputPath = string.Format(@"C:\Pdk\Temp\Output\{0}.pdf", guid);
                workBook.Save(path, saveOptions);
                var process = new Process
                                  {
                                      StartInfo = new ProcessStartInfo(@"C:\Pdk\pdftk.exe", string.Format("\"{0}\" cat 1-endE output \"{1}\"", path, outputPath))
                                                      {
                                                          UseShellExecute = false
                                                      }
                                  };
                process.Start();
                process.WaitForExit();
                var pdfFileStream = new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                var pdfBuffer = new byte[pdfFileStream.Length];
                pdfFileStream.Read(pdfBuffer, 0, (int) pdfFileStream.Length);
                return pdfBuffer;
            }
            var pdfStream = new MemoryStream();
            workBook.Save(pdfStream, saveOptions);
            return pdfStream.ToArray();
        }

        #endregion
    }
}